#!/usr/bin/env python
# -*- coding: utf8 -*-

''' 
# =======
# User: luwei
# Date: 11-4-21
# Time: 上午9:00
# email = luw2007@gmail.com
# =======
'''

# Imports
# =======

import socket
import sys
import re

def check_server(address, port):
    #creat a Tcp socket
    s = socket.socket()
    print "Attempting to connect to " , address , "on the port" , port
    try:
        s.connect((address, port))
        print "Connect to " , address , "on the port" , port
        return True
    except socket.error, e:
        print "Connect to " , address , "on the port" , port , "failed: " , e
        return False

def check_server_input():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-a', "--address", dest="address", default="baidu.com", help="ADDRESS for the server", metavar="ADDRESS")
    parser.add_option('-p', "--port", dest="port", type="int", default="80", help="PORT for the server", metavar="PORT")

    (options, args) = parser.parse_args()
    print "options: " , options , "args: " , args
    check = check_server(options.address, options.port)
    print "check_server resturn" , check
    sys.exit(not check)

def check_web_server(address, port, resource):
    #Build up HTTP request string
    if not resource.startswith('/'):
        resource = '/' + resource
    #request_string = "GET " + resource + " HTTP/1.1\r\nHOST: " + address + "\r\n\r\n"
    request_string = "GET %s HTTP/1.1\r\nHOST: %s \r\n\r\n" % (resource, address)
    print "HTTP request"
    print "|||", request_string, "|||"
    #creat a TCP socket
    s = socket.socket()
    print "Attempting to connect to " , address , "on the port" , port
    try:
        s.connect((address, port))
        print "Connect to " , address , "on the port" , port
        s.send(request_string)
        #noly get the first 100 bytes
        rsp = s.recv(1000)
        print "Recived 100 bytes of HTTP response"
        print "|||", rsp, "|||"
    except socket.error, e:
        print "Connect to " , address , "on the port" , port , "failed: " , e
        return False
    finally:
        print "Closing the connection"
        s.close()
    lines = rsp.splitlines()
    print "First line of HTTP response: %s " % lines[0]
    try:
        version, status, message = re.split(r'\s+', lines[0], 2)
        print "Version: ", version, "Status: ", status, "Message: ", message
    except ValueError:
        print "Failed to split status line"
        return False
    if status in ['200', '301']:
        print "Success -status was ", status
        return
    else:
        print "Status was ", status
        return False

def check_web_server_input():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-a', "--address", dest="address", default="www.baidu.com", help="ADDRESS for the server", metavar="ADDRESS")
    parser.add_option('-p', "--port", dest="port", type="int", default="80", help="PORT for the server", metavar="PORT")
    parser.add_option('-r', "--resource", dest="resource", default="index.html", help="RESOURCE to check", metavar="RESOURCE")

    (options, args) = parser.parse_args()
    print "options: " , options , "args: " , args
    check = check_web_server(options.address, options.port, options.resource)
    print "check_web_server resturn " , check
    sys.exit(not check)

def check_web_server_by_host(address, port, host, resource):
    #Build up HTTP request string
    if not resource.startswith('/'):
        resource = '/' + resource
    #request_string = "GET" + resource + "HTTP/1.1\r\nHOST: " + address + "\r\n\r\n"
    request_string = "GET %s HTTP/1.1\r\nHOST: %s \r\n\r\n" % (resource, host)
    print "HTTP request"
    print "|||", request_string, "|||"

    # creat a TCP socket
    s = socket.socket()
    print "Attempting to connect to " , address , "on the port" , port
    try:
        s.connect((address, port))
        print "Connect to " , address , "on the port" , port
        s.send(request_string)
        # noly get the first 100 bytes
        rsp = s.recv(100)
        print "Recived 100 bytes of HTTP response"
        print "|||", rsp, "|||"
    except socket.error, e:
        print "Connect to " , address , "on the port" , port , "failed: " , e
        return False
    finally:
        print "Closing the connection"
        s.close()
    lines = rsp.splitlines()
    print "First line of HTTP response: %s " % lines[0]
    try:
        version, status, message = re.split(r'\s+', lines[0], 2)
        print "Version: ", version, "Status: ", status, "Message: ", message
    except ValueError:
        print "Failed to split status line"
        return False
    if status in ['200', '301']:
        print "Success -status was ", status
        return
    else:
        print "Status was ", status
        return False

def check_web_server_by_host_input():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-a', "--address", dest="address", default="61.135.169.125", help="ADDRESS for the server", metavar="ADDRESS")
    parser.add_option('-p', "--port", dest="port", type="int", default="80", help="PORT for the server", metavar="PORT")
    parser.add_option('-H', "--host", dest="host", default="www.baidu.com", help="hostname for the server", metavar="HOST")
    parser.add_option('-r', "--resource", dest="resource", default="index.html", help="RESOURCE to check", metavar="RESOURCE")

    (options, args) = parser.parse_args()
    print "options: " , options , "args: " , args
    check = check_web_server_by_host(options.address, options.port, options.host, options.resource)
    print "check_web_server resturn " , check
    sys.exit(not check)

def check_web_server_by_domain(domain, port, resource):
    #Build up HTTP request string
    import network
    domain_list = network.get_address_by_server(domain,"8.8.8.8")
    #print domain_list
    address = domain_list[0]
    if not resource.startswith('/'):
        resource = '/' + resource
    #request_string = "GET" + resource + "HTTP/1.1\r\nHOST: " + address + "\r\n\r\n"
    request_string = "GET %s HTTP/1.1\r\nHOST: %s \r\n\r\n" % (resource, domain)
    print "HTTP request"
    print "|||", request_string, "|||"

    # creat a TCP socket
    s = socket.socket()
    print "Attempting to connect to " , address , "on the port" , port
    try:
        s.connect((address, port))
        print "Connect to " , address , "on the port" , port
        s.send(request_string)
        # noly get the first 100 bytes
        rsp = s.recv(100)
        print "Recived 100 bytes of HTTP response"
        print "|||", rsp, "|||"
    except socket.error, e:
        print "Connect to " , address , "on the port" , port , "failed: " , e
        return False
    finally:
        print "Closing the connection"
        s.close()
    lines = rsp.splitlines()
    print "First line of HTTP response: %s " % lines[0]
    try:
        version, status, message = re.split(r'\s+', lines[0], 2)
        print "Version: ", version, "Status: ", status, "Message: ", message
    except ValueError:
        print "Failed to split status line"
        return False
    if status in ['200', '301', '302']:
        print "Success -status was ", status
        return
    else:
        print "Status was ", status
        return False

def check_web_server_by_domain_input():
    from optparse import OptionParser
    parser = OptionParser()
    #parser.add_option('-a', "--address", dest="address", default="61.135.169.125", help="ADDRESS for the server", metavar="ADDRESS")
    parser.add_option('-p', "--port", dest="port", type="int", default="80", help="PORT for the server", metavar="PORT")
    parser.add_option('-d', "--domain", dest="domain", default="www.zlgn.com", help="hostname for the server", metavar="HOST")
    parser.add_option('-r', "--resource", dest="resource", default="index.html", help="RESOURCE to check", metavar="RESOURCE")
    
    (options, args) = parser.parse_args()

    if args:
        domain = args[0]
    else:
        domain = options.domain

    print "options: " , options , "args: " , args
    check = check_web_server_by_domain(domain, options.port, options.resource)
    print "check_web_server resturn " , check
    sys.exit(not check)


def main():
    '''test main'''
    print "done"

if __name__ == '__main__':
    #check_web_server_input()
    check_web_server_by_domain_input()
    main()
